<template>
  <view class="">
    <remind-carinfo :dataBean="dataBean"></remind-carinfo>

    <view class="item" style="padding: 20rpx;">
      <u-form class="item" style="padding: 0 20rpx 110rpx;" :model="carRepair" ref="uform" :rules="rules"
              label-width="auto">

        <u-form-item label="维修厂名称" borderBottom>
          <u-input v-model="carRepair.serviceName" border="none" inputAlign="right" placeholder="请输入">
          </u-input>
        </u-form-item>

        <u-form-item label="维修开始时间" @click="pickerShow(1)" borderBottom>
          <u-input v-model="carRepair.repairStartDate" disabled disabledColor="#ffffff" border="none" inputAlign="right"
                   placeholder="请选择" type="select" :select-open="actionSheetShow">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="维修结束时间" @click="pickerShow(3)" borderBottom>
          <u-input v-model="carRepair.repairEndDate" disabled disabledColor="#ffffff" border="none" inputAlign="right"
                   placeholder="请选择结束时间" type="select" :select-open="actionSheetShow">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="车辆公里数" borderBottom prop="carMileage">
          <u-input ref="carMileage" v-model="carRepair.carMileage" border="none" inputAlign="right" maxlength="7"
                   placeholder="请输入">
          </u-input>
        </u-form-item>

        <u-form-item label="故障描述" borderBottom>
          <u-input v-model="carRepair.faultDesc" border="none" inputAlign="right" placeholder="请输入">
          </u-input>
        </u-form-item>

        <u-form-item label="维修报价" borderBottom prop="repairShopQuotation">
          <u-input v-model="carRepair.repairShopQuotation" type="digit" border="none" inputAlign="right"
                   placeholder="请输入">
          </u-input>
        </u-form-item>

        <u-form-item label="维修内容" borderBottom>
          <u-input v-model="carRepair.repairContent" border="none" inputAlign="right" placeholder="请输入">
          </u-input>
        </u-form-item>

        <u-form-item label="司机电话" prop="driverPhone" borderBottom>
          <u-input v-model="carRepair.driverPhone" border="none" inputAlign="right" placeholder="请输入" maxlength="11">
          </u-input>
        </u-form-item>

        <u-form-item label="是否已结算" @click="pickerShow(4)" borderBottom>
          <u-input v-model="carRepair.costSettlementName" disabled disabledColor="#ffffff" border="none"
                   inputAlign="right"
                   placeholder="请选择是或否" type="select" :select-open="actionSheetShow">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="维修相关费用信息" borderBottom @click="handleAdd">
          <u-input disabled disabledColor="#ffffff" border="none" inputAlign="right" type="select">
          </u-input>
          <u-icon slot="right" name="plus"/>
        </u-form-item>

        <u-collapse v-if="carRepair.relatedCostsList.length > 0">
          <u-collapse-item v-for="(item,index) in carRepair.relatedCostsList" :title="`维修相关费用信息${index}`"
                           name="Numerous tools">
            <collapse-page v-model="carRepair.relatedCostsList[index]"
                           :payeeList="payeeList" @delete="handleDele(index)"/>
          </u-collapse-item>
        </u-collapse>

        <u-form-item label="维修反馈意见">
          <u-input v-model="carRepair.repairFeedback" border="none" inputAlign="right" placeholder="请输入反馈意见">
          </u-input>
        </u-form-item>

        <u-form-item label="维修是否提供备用车" @click="pickerShow(2)" borderBottom>
          <u-input v-model="carRepair.isSpareCarShow" disabled disabledColor="#ffffff" border="none" inputAlign="right"
                   placeholder="请选择" type="select">
          </u-input>
          <u-icon slot="right" name="arrow-right"></u-icon>
        </u-form-item>

        <u-form-item label="备用车牌号" v-if="spareCarNoShow" borderBottom>
          <u-input v-model="carRepair.spareCarNo" border="none" inputAlign="right" placeholder="请输入">
          </u-input>
        </u-form-item>

        <u-form-item label="备注" borderBottom>
          <u-input v-model="carRepair.remark" border="none" inputAlign="right" placeholder="请输入备注">
          </u-input>
        </u-form-item>

        <!--				<u-form-item label="维修项目明细" borderBottom @click="goSelItem">-->
        <!--					<u-input v-model="maintenanceTypeStr" border="none" inputAlign="right" disabled="true" disabledColor="#ffffff"-->
        <!--						placeholder="添加明细" type="select" :select-open="actionSheetShow">-->
        <!--					</u-input>-->
        <!--					<u-icon slot="right" name="arrow-right"></u-icon>-->
        <!--				</u-form-item>-->

        <!--				<u-form-item label="维修价格用户支付租金" borderBottom>-->
        <!--					<u-input ref="userPay"  v-model="carRepair.userPay" type="digit" border="none" inputAlign="right"-->
        <!--						placeholder="请输入">-->
        <!--					</u-input>-->
        <!--				</u-form-item>-->

        <!--				<u-form-item label="维修价格平台支付金额" borderBottom>-->
        <!--					<u-input ref="platformPay" v-model="carRepair.platformPay" type="digit" border="none" inputAlign="right"-->
        <!--						placeholder="请输入">-->
        <!--					</u-input>-->
        <!--				</u-form-item>-->

        <!--				<u-form-item label="维修价格保险支付金额" borderBottom>-->
        <!--					<u-input ref="insurancePay" v-model="carRepair.insurancePay" type="digit" border="none" inputAlign="right"-->
        <!--						placeholder="请输入">-->
        <!--					</u-input>-->
        <!--				</u-form-item>-->
        <!--				<u-form-item label="总金额" borderBottom>-->
        <!--					<u-input v-model="totalMoney" type="digit" border="none" inputAlign="right"-->
        <!--						placeholder="0" readonly>-->
        <!--					</u-input>-->
        <!--				</u-form-item>-->

        <text style="padding: 20rpx 0; display: block;font-size: 30rpx;color: #333;">维修附件</text>

        <lr-upload ref="upload1" @on-change='onListChange' :tag="1" :objType="9"></lr-upload>

      </u-form>

    </view>

    <examflow :from="pageType" :instanceId="instanceId" approvalName="carRepairApprove" :isAdd="'add'==pageType">
    </examflow>

    <!-- 维修开始时间 -->
    <u-datetime-picker v-model="value1" :maxDate="value2" :show="startTimeShow" mode="date" @confirm="timeconfirm"
                       @cancel="startTimeShow=false">
    </u-datetime-picker>

    <!-- 维修结束时间 -->
    <u-datetime-picker v-model="value2" :minDate="value1" :show="endTimeShow" mode="date" @confirm="timeconfirm"
                       @cancel="endTimeShow=false">
    </u-datetime-picker>

    <!-- <u-picker :mode="mode" v-model="startTimeShow" @confirm="pickerConfim()"></u-picker> -->
    <!-- 是否提供备用车 -->
    <u-picker :show="reservedCarShow" :columns="isSpareCarList" keyName="value" @confirm="pickerConfim"
              @cancel="reservedCarShow=false"></u-picker>

    <!-- 是否已结算 -->
    <u-picker :show="settleShow" :columns="settleList" keyName="value" @confirm="pickerConfim"
              @cancel="settleShow=false"></u-picker>

    <!-- <u-picker :mode="mode" v-model="reservedCarShow" :default-selector="[0]" :range="isSpareCarList"
      range-key="value" @confirm="pickerConfim()"></u-picker> -->

    <u-modal ref="uModal" :show="showModal" :show-cancel-button="true" show-title="" @confirm="confirm"
             content="确定提交？"
             @cancel="showModal=false">
      <!-- #ifndef MP-WEIXIN || MP-TOUTIAO -->
      <!-- <view class="warp" style="margin: 30rpx;" v-if="contentSlot">
        <image class="logo" src="https://uviewui.com/common/logo.png" style="width: 220rpx;"
          mode="widthFix"></image>
      </view> -->
      <!-- #endif -->
    </u-modal>
    <view style="height: 100rpx;"></view>
    <view class="button-container">
      <button class="btn-item" @click="commit">提 交</button>
    </view>
  </view>
</template>

<script>
import remindCarinfo from "../../../components/remind-carinfo.vue";
import lrUpload from "../../../components/global/lr-upload.vue";
import examflow from "@/components/exam-flow.vue";
import {isVideo} from "@/common/calc";
import collapsePage from "./collapsePage.vue";

export default {
  components: {
    remindCarinfo,
    lrUpload,
    examflow,
    collapsePage,
  },
  data() {
    return {

      refsList: ["carMileage", "userPay", "platformPay", "insurancePay"],
      totalMoney: 0,
      // value1:Number(new Date())-3*365*24*3600*1000,
      // value2:Number(new Date())+30*24*3600*1000,
      value1: Number(new Date()),
      value2: Number(new Date()) + 12 * 30 * 24 * 3600 * 1000,
      dataBean: {
        vehicle: {},
        carRepair: {},
      },
      isSpareCarList: [
        [
          {
            value: "是",
            code: 1,
          },
          {
            value: "否",
            code: 2,
          },
        ],
      ],
      settleList: [
        [
          {
            value: "是",
            code: 2,
          },
          {
            value: "否",
            code: 1,
          },
        ],
      ],
      carRepair: {
        carId: "",
        driverPhone: "",
        carMileage: "",
        repairStartDate: "",
        repairEndDate: "",
        faultDesc: "",
        serviceName: "",
        repairShopQuotation: "",
        repairContent: "",
        userPay: "",
        platformPay: "",
        insurancePay: "",
        isSpareCar: 2,
        isSpareCarShow: "",
        costSettlement: "",
        costSettlementName: "",
        spareCarNo: "",
        remark: "",
        repairFeedback: "",
        attachment: [],
        relatedCostsList: [],
      },
      rules: {
        carMileage:[
          {
            validator: (rule, value, callback) => {
              return   /^(?:[1-9]\d*|0)(?:\.\d{0,2})?$/.test(value);
            },
            message: '请输入整数或者保留两位小数',
            trigger: ['change', 'blur'],
          }
        ],
        repairShopQuotation:[
          {
            validator: (rule, value, callback) => {
              return   /^(?:[1-9]\d*|0)(?:\.\d{0,2})?$/.test(value);
            },
            message: '请输入整数或者保留两位小数',
            trigger: ['change', 'blur'],
          }
        ]
      },
      mode: "",
      type: 0,
      spareCarNoShow: false,
      startTimeShow: false,
      reservedCarShow: false,
      showModal: false,
      endTimeShow: false,
      settleShow: false,
      pageType: "",
      instanceId: "",
      businessId: "",
      carId: "",
      maintenanceTypeStr: "",
      repairItemInfoList: [],
      restart: "",
      tableData: [],
      payeeList: []
    };
  },
  onLoad(options) {
    if (!uni.$u.test.isEmpty(options.vehicle)) {
      var data = JSON.parse(options.vehicle); //字符串转对象
      this.dataBean.vehicle = data;
    }

    this.carRepair.serviceName =
        this.$store.state.user.userInfo.officialPartner || "";
    console.log(this.$store.state.user.userInfo, "--");
    this.pageType = options.pageType;
    this.instanceId = options.instanceId;
    this.businessId = options.businessId;
    this.carId = options.carId;
    this.restart = options.restart;

    let that = this;

    if ("add" == this.pageType) {
      uni.setNavigationBarTitle({
        title: "新增车辆维修",
      });
    } else if ("edit" == this.pageType) {
      uni.setNavigationBarTitle({
        title: "编辑车辆维修",
      });

      this.$u.api
          .repairDetail({
            carId: this.carId,
            businessId: this.businessId,
          })
          .then((res) => {
            if (1 == this.restart) {
              //重新发起的id要置为空
              res.carRepair.id = null;
            }
            this.dataBean = res;
            this.carRepair = res.carRepair;

            this.carRepair.isSpareCarShow =
                1 == this.carRepair.isSpareCar ? "是" : "否";
            if (1 == this.carRepair.isSpareCar) {
              this.spareCarNoShow = true;
            } else {
              this.spareCarNoShow = false;
            }

            if (
                this.carRepair &&
                this.carRepair.repairItemInfoList &&
                !uni.$u.test.isEmpty(this.carRepair.repairItemInfoList)
            ) {
              let str =
                  "已添加" +
                  this.carRepair.repairItemInfoList.length.toString() +
                  "项";
              this.maintenanceTypeStr = str;

              this.repairItemInfoList = this.carRepair.repairItemInfoList;
            }

            this.carRepair.costSettlementName =
                2 == this.carRepair.costSettlement ? "是" : "否";

            if (!uni.$u.test.isEmpty(this.carRepair.attachment)) {
              this.$refs.upload1.fileList1 = this.carRepair.attachment
                  .filter((item) => {
                    return 1 == item.type_file || 1 == item.typeFile;
                  })
                  .map((item) => {
                    return {
                      ...item,
                      message: "",
                      size: 52363,
                      status: "success",
                      thumb: that.baseImgUrl() + item.url,
                      type: isVideo(item.url),
                      url: item.url,
                    };
                  });
            }
          });
    }
  },
  watch: {
    carRepair: {
      deep: true,
      handler(newVal, oldVal) {
        let singleMoney = Number(newVal.userPay || 0)
            .add(Number(newVal.platformPay || 0))
            .add(Number(newVal.insurancePay || 0));
        let bothMoney = this.repairItemInfoList.reduce((total, num) => {
          return Number(num.itemMoney || 0).add(total);
        }, 0);
        // this.totalMoney = singleMoney.add(bothMoney);
      },
      immediate: false,
    },
    repairItemInfoList: {
      deep: true,
      handler(newVal, oldVal) {
        console.log(newVal);
        console.log(oldVal);
        let singleMoney = Number(this.carRepair.userPay || 0)
            .add(Number(this.carRepair.platformPay || 0))
            .add(Number(this.carRepair.insurancePay || 0));
        let bothMoney = newVal.reduce((total, num) => {
          return Number(num.itemMoney || 0).add(total);
        }, 0);
        // this.totalMoney = singleMoney.add(bothMoney);
      },
      immediate: false,
    },
  },
  mounted() {
    // let that = this;
    // that.$nextTick(function () {
    //   setTimeout(() => {
    //     that.refsList.map((item) => {
    //       that.$refs[item]?.setFormatter((e) => {
    //         return e
    //             .replace(/[^\d.]/g, "")
    //             .replace(/\.{2,}/g, ".")
    //             .replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
    //       });
    //     });
    //   }, 1000);
    // });
    this.handleList()
  },
  methods: {
    handleList() {
      this.$u.api.getPayeeList({carId: this.dataBean.vehicle.carId}).then(res => {
        this.payeeList = res || []
      })
    },

    handleAdd() {
      let obj = {
        feeName: "",
        receivableAmount: "",
        receivableObjName: "",
        receivedTime: "",
        isGenerateReceivableBill: 0,
        payableAmount: "",
        paymentObjName: "",
        payTime: "",
        isGeneratePayableBill: 0,
      };
      this.carRepair.relatedCostsList.push(obj);
    },

    handleDele(index) {
      this.carRepair.relatedCostsList.splice(index, 1);
    },

    goSelItem() {
      var intentData = JSON.stringify(this.repairItemInfoList);
      uni.navigateTo({
        url: "./maintenancetype?repairItemInfoList=" + intentData,
      });
    },
    pickerShow(type) {
      this.type = type;
      switch (type) {
        case 1: //维修开始时间
          this.startTimeShow = true;
          this.mode = "time";
          break;
        case 2:
          this.reservedCarShow = true;
          this.mode = "selector";
          break;
        case 3:
          this.endTimeShow = true;
          this.mode = "time";
          break;
        case 4:
          this.settleShow = true;
          this.mode = "selector";
          break;
      }
    },

    timeconfirm(e) {
      let timeStr = uni.$u.timeFormat(e.value, "yyyy-mm-dd");

      if (this.type == 1) {
        //维修开始时间
        this.startTimeShow = false;
        this.carRepair.repairStartDate = timeStr;
      } else if (this.type == 3) {
        //结束时间
        this.endTimeShow = false;
        this.carRepair.repairEndDate = timeStr;
      }
    },

    pickerConfim(e) {
      if (this.type == 2) {
        //是否提供备用车
        this.reservedCarShow = false;
        let obj = e.value[0];
        this.carRepair.isSpareCar = obj.code;
        this.carRepair.isSpareCarShow = obj.value;
        if (obj.code == 1) {
          this.spareCarNoShow = true;
        } else {
          this.spareCarNoShow = false;
        }
      } else if (this.type == 4) {
        this.settleShow = false;
        this.carRepair.costSettlement = e.value[0].code;
        this.carRepair.costSettlementName = e.value[0].value;
      }
      // }
    },

    onListChange(tag, list, objList) {
      if (tag == 1) {
        this.carRepair.attachment = objList;
      }
    },

    commit() {
      let that = this;
      uni.showModal({
        content: "确定提交吗?",
        success(result) {
          if (result.confirm) {
            that.confirm();
          }
        },
      });
    },

    confirm() {
      this.dataBean.carRepair = this.carRepair;
      this.dataBean.carRepair.repairItemInfoList = this.repairItemInfoList.map(
          (item, index) => {
            return {...item, serializeId: index + 1};
          }
      );
      this.$u.api.saveRepair(this.dataBean).then((res) => {
        uni.$emit("refresh-repair", true);
        this.$u.toast("提交成功");
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      });
    },
  },
};
</script>

<style lang="scss">
page {
  height: 100%;
}

.bottom {
  position: fixed;
  width: 100%;
  height: 100rpx;
  bottom: 0;
  z-index: 999;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;

  text {
    width: 98%;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 50rpx;
    background-color: $blue15;
    color: white;
    text-align: center;
    font-size: 30rpx;
  }
}
</style>
